< previous page page_119 next page >

Page 119
Writing Code for the Menu Items
After creating the menu's structure, you need to write code to let the menu items actually perform tasks. As with a form or other controls, you do so by writing code in an event procedure. A menu item handles only one event: the Click event. This event is triggered when a user clicks the menu item, or when the user selects the item and presses Enter. Think of the user's action of selecting a menu item as being similar to clicking a command button.
note.gif A menu item's Click event is also triggered when a user uses an access key or shortcut key to access an item. square.gif

To add code to a menu item's Click event procedure, first select the menu item on the form by clicking the item. This action opens a Code window and sets up the Event procedure for the selected item, in the same manner as if you had double-clicked some other object on your form. Then simply type in the code to handle the task.
Now you can enhance the menu example by coding the File, Exit function, as shown in the following steps:
1. In the design environment, click Form1's File menu to open it; then click Exit. You are presented with the Code window for the Click event procedure for your mnuFileExit menu item.
2. Type the following code into the event procedure:
Dim nTemp As Integer, sTemp As String
sTemp = "Are you sure you want to exit?"
nTemp = MsgBox(sTemp, vbYesNo, "Menu Sample Program")  
If nTemp = vbYes Then
      End
End if
3. Close the Code window.
Save and run your test application. When you choose File, Exit from the menu system, you should be presented with a message box asking you to verify your decision to exit the program. If you click the Yes button, your program ends.
Optional Settings
In addition to the required Caption and Name properties, each menu item has several optional properties that you can set either to control the behavior of the menu or to indicate the status of a program option. The most commonly used of these properties are the Visible, Enabled, and Checked properties.
The Visible and Enabled Properties
The menu item's Visible and Enabled properties work just like they do with any other object. When the Visible property is set to True, the menu item is visible to the users. If the Visible property is set to False, the item (and any associated submenus) are hidden from the users. You have probably seen the Enabled and Visible properties used in a word processing program (though you might not have been aware of how it

 
< previous page page_119 next page >